import { Component, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { BiService } from '../../bi.service';
import { AllModules, Module } from '@ag-grid-enterprise/all-modules';
import { GridConfigService } from '@core/config/grid-config.service';
import { GridOptions } from '@ag-grid-community/core';
import { toBoolean } from '@shared/apes/core';
import { RenderTooltipComponent } from '@shared/ag-grid-ext/cell-renders/render-tooltip.component';
import { ApesMessageService } from '@shared/apes/message';

@Component({
  selector: 'store-money',
  templateUrl: './store-money.component.html',
  styleUrls: ['./store-money.component.scss'],
})
export class StoreMoneyComponent implements OnInit {

  /** 按钮相关 **/
  buttonBar = [
    { style: 'primary', label: '查询', id: 'action_query', loading: false },
  ];

  ctx = { model: {} };
  model: any = {};
  field: any[] = [
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '日期',
        config: {
          required: true,
          operators: ['EQ'],
          type: 'dateRange',
        },
        divCol: 6,
        defaultValue: true,
      },
    },
    {
      key: 'DEPT_ID',
      type: 'conditionInput',
      templateOptions: {
        label: '所属门店',
        config: {
          api: 'cm.dept.findAllOperate',
          init: true,
          operators: ['EQ'],
          type: 'select',
          downFormatter: 'value.name',
          valueFormatter: 'value.name',
        },
        domain: '{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
        divCol: 6,
      },
    },
    {
      key: 'COMPANY_ID',
      type: 'conditionInput',
      templateOptions: {
        label: '所属公司',
        config: {
          api: 'cm.partyRole.findAllByCompany',
          init: true,
          operators: ['EQ'],
          type: 'select',
          downFormatter: 'value.name',
          valueFormatter: 'value.name',
        },
        domain: '{"filters":[{"field":"role.id","operator":"EQ","value":"Company"}],"groups":[{"filters":[{"field":"id","operator":"EQ","value":"{{value}}"},{"field":"party.name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}],"operator":"and"}',
        divCol: 6,
      },
    },
  ];
  frameworkComponents = {
    renderTooltip: RenderTooltipComponent,
  };
  showData: any = {};

  modules: Module[] = AllModules;
  localeText: any;
  context = {};
  gridOptions: GridOptions;
  gridApi: any;
  gridColumnApi: any;
  gridData: any[] = [
    {
      id: 'PaymentMethod',
      columnDefs: [
        { headerName: '收款方式', field: 'TYPE', cellRenderer: 'renderTooltip' },
        { headerName: '金额', field: 'AMOUNT', sum: true },
      ],
      rowData: [],
      pinnedBottomRowData: [],
    },
    {
      id: 'BusinessIncome',
      columnDefs: [
        { headerName: '营业收入类型', field: 'TYPE', cellRenderer: 'renderTooltip' },
        { headerName: '金额', field: 'AMOUNT', sum: true },
      ],
      rowData: [],
      pinnedBottomRowData: [],
    },
    {
      id: 'AdvancesReceived',
      columnDefs: [
        { headerName: '预收款类型', field: 'TYPE', cellRenderer: 'renderTooltip' },
        { headerName: '金额', field: 'AMOUNT', sum: true },
      ],
      rowData: [],
      pinnedBottomRowData: [],
    },
    {
      id: 'CrossCompany',
      columnDefs: [
        { headerName: '会员联盟', field: 'TYPE', cellRenderer: 'renderTooltip' },
        { headerName: '金额', field: 'AMOUNT', sum: true },
      ],
      rowData: [],
      pinnedBottomRowData: [],
    },
    {
      id: 'LossCollection',
      columnDefs: [
        { headerName: '代收款类型', field: 'TYPE', cellRenderer: 'renderTooltip' },
        { headerName: '金额', field: 'AMOUNT', sum: true },
      ],
      rowData: [],
      pinnedBottomRowData: [],
    },
  ];


  constructor(
    private apiService: ApiService,
    private bi: BiService,
    protected gridConfigService: GridConfigService,
    private msg: ApesMessageService
  ) {
    this.gridData.forEach((item) => {
      item['gridOptions'] = <GridOptions>{
        suppressExcelExport: true,
        suppressCsvExport: true,
        showToolPanel: false,
      };
      item.gridOptions.localeText = this.gridConfigService.getLocaleText();
    });
  }

  ngOnInit() {

  }

  onEvent(event) {
    this.queryData();
  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
    this.gridApi.sizeColumnsToFit();
  }

  queryData() {
    if(this.model['DATE'].length == 0){
      this.msg.error('请选择日期');
      return ;
    }
    let dateItem = this.bi.conversionMonths(this.model['DATE'], 6);

    this.showData = {};
    this.gridData.forEach((item) => {
      item['rowData'] = [];
      item['pinnedBottomRowData'] = [];
    });

    const resData = {
      DATE_START: dateItem[0],
      DATE_END: dateItem[1],
      DEPT_ID: this.model['DEPT_ID'],
      COMPANY_ID: this.model['COMPANY_ID'],
    };
    let api = 'capital.report.query';

    this.apiService.post(api, { 'body': JSON.stringify(resData) }).subscribe((body) => {
      if (body) {
        // console.log(body);
        this.showData = this.extend(body);
        this.gridData.forEach((item) => {
          let key = item.id;
          item['rowData'] = body[key];
          if (item['rowData'] && item['rowData'].length != 0) {
            let AMOUNT = 0;
            item.rowData.forEach((i) => {
              AMOUNT += i.AMOUNT;
            });
            let sumFieldObj = this.getSumField(item);
            if (sumFieldObj.sumFieldList.length > 0) {
              item['pinnedBottomRowData'] = this.setPinnedBottomRowData(sumFieldObj.fieldObj, sumFieldObj.sumFieldList, [{ AMOUNT: AMOUNT.toFixed(2) }], item.rowData.length);
            }
          }
        });
      }
    });
  }

  getSumField(item) {
    const sumFieldList = [];
    const fieldObj = {};
    let sumOption = {};
    let sumFieldStr = '';
    const columnList = item.columnDefs;
    for (let i = 0, lent = columnList.length; i < lent; i++) {
      const columnObj = columnList[i];
      fieldObj[columnObj['field']] = '';

      if (columnObj['sum'] && toBoolean(columnObj['sum'])) {
        sumFieldList.push(columnObj['field']);
        sumFieldStr += `${columnObj['field']};`;
        sumOption[columnObj['field']] = { scale: columnObj['scale'] ? columnObj['scale'] : 2 };
      }
    }
    return { sumFieldList: sumFieldList, fieldObj: fieldObj, sumOption: sumOption, sumFieldStr: sumFieldStr };
  }

  setPinnedBottomRowData(fieldObj, sumFieldList, sumResultList, bRow) {
    if (bRow > 0) {
      for (let i = 0, len = sumFieldList.length; i < len; i++) {
        const fieldKey = sumFieldList[i];
        fieldObj[fieldKey] = sumResultList[0][fieldKey];
      }
    } else {
      fieldObj = [];
    }
    fieldObj['hideBtnBar'] = 'true';

    return [fieldObj];
  }

  protected extend(data: any) {
    const result = {};
    for (const key in data) {
      const value = data[key];
      result[key] = value;
    }
    return result;
  }

}

